
# Mail Sender - send email or text
# @author: David Emole
# Created on 10/05/2013


import smtplib, getopt, sys, time
from datetime import datetime
import ConfigParser

# Mail Config file - this contains the sender's email address, username and password 
mailconfig_path = 'mailconfig.cfg'


class MailSender:
    def __init__(self, config_file_path):
        # Load config
        config = ConfigParser.ConfigParser()
        config.read(config_file_path)
        
        # Get email account credentials
        self.username = config.get('email', 'user')
        self.password = config.get('email', 'password')
        self.from_name = config.get('email', 'name')
        self.sender = config.get('email', 'sender')
        self.phoneNumberAsEmail = config.get('phone', 'phone-email')
        

    def sendEmail(self, subject, msg, recipient):
        #Check recipient. If none specified, send to self
        if recipient is None or len(recipient) == 0:
            recipient = self.sender
        
        #Send an email using the email account.
        senddate=datetime.strftime(datetime.now(), '%Y-%m-%d')
        m="Date: %s\r\nFrom: %s <%s>\r\nTo: %s\r\nSubject: %s\r\nX-Mailer: My-Mail\r\n\r\n" % (senddate, self.from_name, self.sender, recipient, subject)
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.starttls()
        server.login(self.username, self.password)
        server.sendmail(self.sender, recipient, m+msg)
        server.quit()


    def sendText(self, subject, msg):
        self.sendEmail(subject, msg, self.phoneNumberAsEmail)


        
#
# Main Function
#
def main():
    # Parameters
    send_email = False
    send_text = False
    subject = ''
    message = ''
    recipient = ''

    # Read arguments
    opts, args = getopt.getopt(sys.argv[1:], "hets:m:", ["subject=","message=","recipient=", "help"])
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            printUsage()
        elif opt == "-e":
            send_email = True
        elif opt == "-t":
            send_text = True
        elif opt in ("-s", "--subject"):
            subject = arg
        elif opt in ("-m", "--message"):
            message = arg
        elif opt in ("--recipient"):
            recipient = arg
        else:
            exit('The option ' + opt + ' is not recognized.')


    # Check input Parameters
    if not (send_email or send_text):
        print("You must choose to send email (-e) or send text (-t)")
        printUsage()
    if message == '' and subject == '':
        print("The Subject and Message cannot be empty at the same time.")
        printUsage()
        

    # Initialize Mail Sender
    mailSender = MailSender(mailconfig_path)
    
    # Send Email
    if send_email:
        log("Sending email to " + (recipient if (recipient != '') else 'self'))
        mailSender.sendEmail(subject, message, recipient)
        log("Email sent")
    
    # Send Text
    if send_text:
        log("Sending text to " + mailSender.phoneNumberAsEmail.split('@')[0])
        mailSender.sendText(subject, message)
        log("Text sent.")


# Print Usage Info
def printUsage():
    print('Mail Sender - sends email or text')
    print('The sender\'s email setup is specified in the config file: mailconfig.cfg')
    print('\nUsage Example:\nSend Email: mailSender.py -e -s "Subject" -m "Message" -r "Recipient"')
    print('Send Text: mailSender.py -t -m "Message" \n')
    print('\t-e\t\tsend email (-e or -t must be specified)')
    print('\t-t\t\tsend text (-e or -t must be specified)')
    print('\t-s,--subject\tSubject')
    print('\t-m,--message\tMessage')
    print('\t-r,--recipients\tRecipient\'s email (optional if sending to self.)\n')
    exit();
    
    
def log(logmsg):
    print("{}\t{}".format(time.strftime("%Y-%m-%d %H:%M:%S"), logmsg))


if __name__ == '__main__':main()
